<?php

require_once dirname(__DIR__) . '/config/db.config.php';

class db
{
    public $conn;
    public $conf;
    public $database;
    public static $sql;
    public static $instance=null;

    private function __construct($conf = array())
    {
        if(empty($conf))
        {
            $conf = $GLOBALS['defaultConf'];
        }
        $this->conf = $conf;
        $this->database = $conf['database'];

        $this->connect($this->conf);
    }

    public static function getInstance($conf = array())
    {
        if(is_null(self::$instance))
        {
            self::$instance = new db($conf);
        }

        return self::$instance;
    }

    public function connect($conf = array())
    {
        empty($conf) && $conf = $this->conf;
        $this->conn = @mysql_connect($conf['host'], $conf['user'], $conf['pwd']);
        if(!$this->conn)
        {
            throw new Exception(mysql_error($this->conn));
        }
    }

    public function selectDb($database = '')
    {
        if(!$this->conn)
        {
            throw new Exception(mysql_error($this->conn));
        }
        $database || $database = $this->database;
        if(!@mysql_select_db($database, $this->conn))
        {
            throw new Exception(mysql_error($this->conn));
        };

        $this->conf['charset'] && @mysql_query("set names {$this->conf['charset']}", $this->conn);
    }

    public function getOne($sql)
    {
        if(!$this->conn)
        {
            $this->connect();
            $this->selectDb();
        }

        $result = mysql_query($sql, $this->conn);
        $data = array();
        if(is_resource($result))
        {
            $data = mysql_fetch_assoc($result);
        }

        return $data;
    }

    public function getAll($sql)
    {
        if(!$this->conn)
        {
            $this->connect();
            $this->selectDb();
        }

        $result = mysql_query($sql, $this->conn);
        $data = array();

        if(is_resource($result))
        {
            while($row = mysql_fetch_assoc($result))
            {
                $data[] = $row;
            }
        }

        return $data;
    }

    public function query($sql)
    {
        if(!$this->conn)
        {
            $this->connect();
            $this->selectDb();
        }

        $result = mysql_query($sql, $this->conn);

        return $result;
    }

    public function __destruct()
    {
        if(is_resource($this->conn))
        {
            mysql_close($this->conn);
        }
    }
}